from pydantic import BaseModel, validator
from typing import Optional, List
from datetime import datetime
from enum import Enum

class UserRole(str, Enum):
    ADMIN = "admin"
    USER = "user"

# 用户相关模型
class UserBase(BaseModel):
    username: str
    name: str
    role: UserRole = UserRole.USER

class UserCreate(UserBase):
    password: str

class UserLogin(BaseModel):
    username: str
    password: str

class UserResponse(UserBase):
    id: int
    
    class Config:
        from_attributes = True

class LoginResponse(BaseModel):
    success: bool
    message: str
    user: Optional[UserResponse] = None
    token: Optional[str] = None

# 商品相关模型
class ProductBase(BaseModel):
    product_name: str
    price: float
    category: str
    stock: int
    sales: int
    
    @validator('price')
    def validate_price(cls, v):
        if v <= 0:
            raise ValueError('价格必须大于0')
        return v
    
    @validator('stock')
    def validate_stock(cls, v):
        if v < 0:
            raise ValueError('库存不能为负数')
        return v
    
    @validator('sales')
    def validate_sales(cls, v):
        if v < 0:
            raise ValueError('销量不能为负数')
        return v

class ProductCreate(ProductBase):
    pass

class ProductUpdate(BaseModel):
    product_name: Optional[str] = None
    price: Optional[float] = None
    category: Optional[str] = None
    stock: Optional[int] = None
    sales: Optional[int] = None

class ProductResponse(ProductBase):
    id: int
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True

class ProductQuery(BaseModel):
    product_name: Optional[str] = None
    category: Optional[str] = None
    min_price: Optional[float] = None
    max_price: Optional[float] = None
    min_stock: Optional[int] = None
    max_stock: Optional[int] = None
    min_sales: Optional[int] = None
    max_sales: Optional[int] = None
    page: int = 1
    page_size: int = 20

class ProductListResponse(BaseModel):
    data: List[ProductResponse]
    total: int
    page: int
    page_size: int
    total_pages: int

class ProductStats(BaseModel):
    total_products: int
    total_categories: int
    average_price: float
    total_stock: int
    total_sales: int
    top_selling: List[ProductResponse]

class APIResponse(BaseModel):
    success: bool
    message: str
    data: Optional[dict] = None